package com.Final.hj;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class PersonSetting extends Fragment{
    private int CHANGECODE;//点击哪一项的值 0 ---修改用户名 1----修改密码 2---修改邮箱

    private LinearLayout changeUname, changePaw,changeEmail, to_login_music, login_vue_music;
    private TextView changeUnameText,changeEmailText, gender_text, type_text, change_show_title;

    private ImageView changeImag;

    private EditText changeEdit;
    private TextView changeShowText;
    private Button changeBtnRe, changeBtnJe, to_exit_login, logou_app;

    private Context personContent;
    private LoginSQLManger sqlInfo;
    private HomeActivity homeActivity;//当前活动的实例

    private String changeFlag;//修改什么数据标识符
    private String data;
    private AlertDialog dlg;


    @Override
    public void onAttach(Context context){
        super.onAttach(context);
        //获取当前content
        personContent = context;
        //获取当前实例
        homeActivity = (HomeActivity) getActivity();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_person_setting, container, false);

        initView(view);

        return view;
    }

    Handler handler = new Handler(){
      @Override
      public void handleMessage(Message msg){
          switch (msg.what){
              case 0:
                  dlg.dismiss();
                  //判断修改的是什么  然后在显示相应的内容
                  if(changeFlag.equals("uname")){
                      changeUnameText.setText(sqlInfo.queryAll().getUname());
                  }else if(changeFlag.equals("email")){
                      changeEmailText.setText(sqlInfo.queryAll().getEmail());
                  }

                  //设置为空
                  changeFlag = "";
                  break;
              default:
                      break;
          }
      }
    };

    //初始化fragment
    public void initView(View view){
        changeUname = (LinearLayout) view.findViewById(R.id.change_uname);
        changePaw = (LinearLayout) view.findViewById(R.id.change_paw);
        changeEmail = (LinearLayout) view.findViewById(R.id.change_email);
        to_login_music = (LinearLayout) view.findViewById(R.id.login_music);
        login_vue_music = (LinearLayout) view.findViewById(R.id.login_vue_music);
        to_exit_login = (Button) view.findViewById(R.id.to_login);
        logou_app = (Button) view.findViewById(R.id.logout_app);

        changeUnameText = (TextView) view.findViewById(R.id.change_uname_text);
        changeEmailText = (TextView) view.findViewById(R.id.change_email_text);
        gender_text = (TextView) view.findViewById(R.id.change_gender_text);
        type_text = (TextView) view.findViewById(R.id.change_type_text);


        changeImag = (ImageView) view.findViewById(R.id.change_img);

        //获取数据库数据 并设置值 管理数据库的对象
        sqlInfo = LoginSQLManger.getInstance(getContext());
        //获取当前数据库的数据
        SQLSavaInfo sqlSavaInfo = sqlInfo.queryAll();

        changeUnameText.setText(sqlSavaInfo.getUname());
        changeImag.setImageResource(Integer.parseInt(sqlSavaInfo.gethImgId()));
        changeEmailText.setText(sqlSavaInfo.getEmail());
        gender_text.setText(sqlSavaInfo.getGender());
        type_text.setText(sqlSavaInfo.getType());
        //修改用户名
        changeUname.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                changeInfo("修改用户名", "请输入你的新用户名");
                changeFlag = "uname";
            }
        });

        //修改密码
        changePaw.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                changeInfo("修改密码", "请输入你的新密码");
                changeFlag = "paw";
            }
        });

        //修改邮箱
        changeEmail.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                changeInfo("修改邮箱", "请输入你的新邮箱");
                changeFlag = "email";
            }
        });

        //听音乐
        to_login_music.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                Intent intent = new Intent(getContext(), MusicApp.class);
                startActivity(intent);
            }
        });

        //网页版
        login_vue_music.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                Intent intent = new Intent(getContext(), TaskJkes.class);
                startActivity(intent);
            }
        });

        //退出当前账号
        to_exit_login.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                Intent intent = new Intent(getContext(), MainActivity.class);
                startActivity(intent);
                //结束销毁当前的活动  后面在师范资源
                getActivity().finish();
            }
        });

        //退出登陆
        logou_app.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                //最好询问一下
                getActivity().finish();
            }
        });
    }

    //初始化弹窗的
    public void initViewDlg(View view){

        changeBtnRe = (Button) view.findViewById(R.id.change_solve);
        changeBtnJe = (Button) view.findViewById(R.id.change_reject);
        changeEdit = (EditText) view.findViewById(R.id.change_edit);
        changeShowText = (TextView) view.findViewById(R.id.change_text);
        change_show_title = (TextView) view.findViewById(R.id.change_show_title);
    }

    public void changeInfo(String showMsg, final String msg){

        AlertDialog.Builder builder = new AlertDialog.Builder(personContent);
        View view = View.inflate(personContent, R.layout.change_info_dlg, null);
        builder.setView(view);

        //初始化变量
        initViewDlg(view);

        dlg = builder.create();

        //显示相应的提示信息
        changeShowText.setText(msg);//提示输入什么
        change_show_title.setText(showMsg);
        changeEdit.setHint(new SpannableString(msg));//动态设置文本框的值

        //取消
        changeBtnJe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dlg.cancel();
            }
        });

        //确认
        changeBtnRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不知道为什么需要final修饰
                sendChange(msg);
//                dlg.dismiss();
            }
        });
        //获取显示的内容
        dlg.show();
    }

    //发送请求修改数据
    public void sendChange(final String msg){
        data = changeEdit.getText().toString().trim();

        if(data.isEmpty()){
            toastMsg(msg);
            return;
        }else if(data.equals(sqlInfo.queryAll().getUname())){
            toastMsg("新用户名正是您现在的用户名，无需重复修改");
            return;
        }else if(data.equals(sqlInfo.queryAll().getPaw())){
            toastMsg("新密码正是您现在的密码，无需重复修改");
            return;
        }else if(data.equals(sqlInfo.queryAll().getEmail())){
            toastMsg("新邮箱正是您现在的邮箱，无需重复修改");
            return;
        }

        //这里需要判断一下是修改什么
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();

                RequestBody requestBody = new FormBody.Builder()
                        .add("id", sqlInfo.queryAll().getMyId())
                        .add("data", data)
                        .add("changeFlag", changeFlag)
                        .build();

                Request request = new Request.Builder()
                        .url("http://192.168.43.124:8080/clogininfo")
                        .post(requestBody)
                        .build();

                Call call = client.newCall(request);

                call.enqueue(new Callback() {
                    @Override
                    public void onFailure( Call call, IOException e) {
                        Log.i("TAG", e.toString());
                    }

                    @Override
                    public void onResponse( Call call, Response response) throws IOException {
                        String string = response.body().string();

                        System.out.println("已经得到数据");
                        //调用函数解析json
                        handle(string);
                    }
                });

            }
        }).start();
    }

    //处理请求
    public void handle(String string){

        if (string.equals("-1")){
            changeEdit.setText("");
            toastShow("修改失败，请稍后再试");
            return;
        }else if(string.equals("0")){
            changeEdit.setText("");
            toastShow("该用户名已经存在，换一个试试");
            return;
        }

        //修改数据
        sqlInfo.updateUser(changeFlag, sqlInfo.queryAll().getMyId(), data);
        //在子线程不能拿主线程的数据  不知道是否可以静态属性的值
        // 因此只能在handle做比较  并且设置最新的值
        handler.sendEmptyMessage(0);
    }

    //子线程提示
    public void toastShow(String showMsg){
        Looper.prepare();
        Toast.makeText(getContext(), showMsg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }
    //主线程提示
    public void toastMsg(String showMsg){
        Toast.makeText(getContext(), showMsg, Toast.LENGTH_SHORT).show();
        changeEdit.setText("");
    }
}
